<template>
  <!-- 门诊医生-处置 -->
  <div class="flex justify-end mb-2"></div>
  <a-table bordered :data-source="dataSource" :columns="cols" :pagination="false" :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'zdlx'">
        <EditCell title="诊断类型">
          <a-select v-model:value="record.zdlx" placeholder="请选择" :virtual="false" :default-open="record.isNew" @select="editRow(record)">
            <a-select-option v-for="item in typeList" :key="item.bm" :value="item.bm">{{ item.mc }}</a-select-option>
          </a-select>
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'zdmc'">
        <EditCell title="诊断名称">
          <SelectTable v-model:value="record.zdmc" type="诊断" @select="(selected) => onSelect(selected, record)" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'zdms'">
        <EditCell title="诊断描述">
          <a-input v-model:value="record.zdms" placeholder="请输入" @blur="editRow(record)" @focus="onInputFocus" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'zdrq'">
        <EditCell title="诊断日期">
          <a-date-picker v-model:value="record.zdrq" :suffix-icon="false" value-format="YYYY-MM-DD" @change="editRow(record)" @focus="onInputFocus" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'zdys'">
        <EditCell title="诊断医生">
          <a-input v-model:value="record.zdys" placeholder="请输入" @blur="editRow(record)" @focus="onInputFocus" />
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <ConfirmModal @confirm="onDelete(record)">
          <a-button type="link" size="small" danger>删除</a-button>
        </ConfirmModal>
      </template>
    </template>
    <template #footer>
      <div class="text-center sticky bottom-0">
        <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" @click="addRow()"> 新增一行 </a-button>
        <a-button type="primary" :icon="h(SaveOutlined)" :disabled="!isHaveNewRow" @click="saveNewRows()"> 保存 </a-button>
      </div>
      <!-- <div class="text-center">
          <a-button type="primary" ghost :disabled="!id" @click="handleAdd">
            <template #icon> <PlusOutlined /> </template>
            添加
          </a-button>
        </div> -->
    </template>
  </a-table>
</template>
<script setup>
import { ref, onMounted, computed, h, watchEffect } from 'vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SelectTable from '@/components/SelectTable'
import ConfirmModal from '@/components/ConfirmModal'
import EditCell from '@/components/EditCell'
import useUserStore from '@/store/user'

const emit = defineEmits(['update:open', 'update:value', 'success'])
import { post } from '@/utils/request'

const { empId } = useUserStore()
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const cols = ref([
  {
    title: '诊断类型',
    dataIndex: 'zdlx',
    width: 130
  },
  {
    title: '诊断名称',
    dataIndex: 'zdmc'
  },
  {
    title: '诊断代码',
    dataIndex: 'zddm',
    width: 130
  },
  {
    title: '诊断描述',
    dataIndex: 'zdms'
  },
  {
    title: '诊断日期',
    dataIndex: 'zdrq',
    width: 130
  },
  {
    title: '诊断医生',
    dataIndex: 'zdys',
    width: 130
  },
  {
    title: '操作',
    width: 130,
    dataIndex: 'operation'
  }
])
const typeList = ref([])
const dataSource = ref([])

const getDiagnosisType = async () => {
  const res = await post('/inp/zyys/getICD10TypeList', {
    zdlb: '诊断类型'
  })
  if (res.code !== 0) return
  typeList.value = res.data
}

const isHaveNewRow = computed(() => {
  return dataSource.value.some((item) => item.isNew)
})
watchEffect(() => props.id && getData())

const getData = async () => {
  const res = await post('/inp/zyys/getPatientDiagnosisInfoList?zybh=' + props.id)
  if (res.code !== 0) return
  dataSource.value = res.data.length ? res.data : [{ key: 'row-0', isNew: true }]
}
const onSelect = (selected, record) => {
  record.zddm = selected.zddm
  record.zdmc = selected.zdmc
  editRow(record)
}

const onDelete = async (row) => {
  const { code, msg } = await post('/inp/zyys/doDelPatientDiagnosis?jbbh=' + row.jbbh)
  if (code !== 0) return message.error(msg || '删除失败')
  message.success('删除成功')
  getData()
}
const addRow = () => {
  const zdrq = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const key = `row-${dataSource.value.length}`
  dataSource.value.push({ key, isNew: true, zdrq })
}

const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    item.zdys = empId
    item.zybh = props.id
    if (item.zddm && item.zybh) {
      emit('success')
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  const { code, msg } = await post('/inp/zyys/doSavePatientDiagnosis', row)
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  getData()
}
onMounted(() => {
  getDiagnosisType()
})
const onInputFocus = (e) => setTimeout(e.target.select(), 100)
</script>
<style lang="less" scoped></style>
